/*
* @Date: 2021/2/23
* @Author: XueChengwu <xuechengwu@erayt.com>
* @Copyright: 2015-2019 Erayt, Inc.
* @Description: If you have some questions, please contact: xuechengwu@erayt.com.
*/
import controller from '../core/controller'
import { get, post } from '../core/route';
import { db, tran, id } from '../core/db/mysql/db';
import Query from '../core/db/mysql/query';
import {login} from '../decorater/auth'
import utils from '../core/utils';
import redis from '../core/db/redis';

@controller()
export default class trade {
  @login
  @post('/api/trade/order')
  async order () {

  }

  @login
  @post('/api/trade/open')
  async open () {
    const userid = this.session;
    const { symbol, cost, side, lot, type, account } = this.params;
    try {
      const msg = await tran(async conn => {
        const limitQuery = new Query(conn, 'bu_limit');
        const userQuery = new Query(conn, 'bu_user');
        const accountQuery = new Query(conn, 'bu_account');
        const accountModal = await accountQuery
          .where('id', account)
          .where('user', userid)
          .find();
        if (!accountModal) {
          return '未找到对应的账户';
        }
        const limitModal = {
          symbol,
          cost,
          sellOrBuy: side,
          type,
          lot,
          addtime: utils.formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss'),
          status: 1,
          user: userid,
          account,
        };
        const lever = accountModal.lever || 1;
        const occupy = Number(cost) * Number(lot) / lever;
        await limitQuery.insert(limitModal);
        if (type === 1) {
          // 开仓，平仓不占用
          await accountModal.where('id', accountModal.id)
            .update({
              occupy: accountModal.occupy + occupy,
              remain: accountModal.remain - occupy,
            });
        }
      });
      if (msg !== undefined) {
        return this.setCode(1).setMsg(msg).json();
      }
      return this.setCode(0).setMsg('开仓成功').json();
    } catch(err) {
      console.log('error====>', err);
      return this.setCode(1).setMsg('系统错误').json();
    }

  }

  @login
  @get('/api/trade/orderList')
  async orderList() {

  }

  @login
  @get('/api/trade/limitList')
  async limitList() {
    const { userid } = this.session;
    try {
      await db(async conn => {
        const limitQuery = new Query(conn, 'bu_limit');
        const limist = await limitQuery.where('user', userid).select();
        this.assign('limits', limist);
      });
      return this.setCode(0).setMsg('获取数据成功').json();
    } catch(err) {
      console.log('error====>', err);
      return this.setCode(1).setMsg('获取数据失败').json();
    }
  }
}
